package com.zcx.test.controller;

import com.zcx.test.common.util.EasyPoiUtils;
import com.zcx.test.common.util.JwtUtils;
import com.zcx.test.common.vo.ApiResult;
import com.zcx.test.common.vo.UserQuery;
import com.zcx.test.pojo.Role;
import com.zcx.test.pojo.User;
import com.zcx.test.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;
import java.net.UnknownHostException;
import java.util.*;
/**
 * @author zhaochangxin
 * @date 2022/3/2 14:35
 */
@Slf4j
// 标识为控制层
@RestController
//API说明该类的作用
@Api(tags = "用户模块")
// 请求一级目录为/user
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    LogController logController;
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    private static final String USER_OPERATION = "success";
    // 登陆常量
    private static final String LOGIN_USER_COOKIE = "loginUser";
    private static final String LOGIN_USER_REDIS_POSITION = "internal_project_zcx:userToken:";
    private static final String LOGIN_SUCCESS = "登陆成功";
    private static final String LOGIN_USER_PASSWORD_ERROR = "密码错误";
    private static final String LOGIN_USER_NOTFOUND = "用户名不存在";
    private static final String PROHIBIT_LOGIN_USER = "用户已被禁止登陆";
    // 注册常量
    private static final String REGISTER_SUCCESS = "注册成功";
    private static final String REGISTER_USERNAME_REPEAT = "用户名已存在";
    // 修改密码常量
    private static final String UPDATE_PASSWORD_SUCCESS = "修改密码成功";
    private static final String THE_SECOND_PASSWORD_IS_INCONSISTENT = "二次重复密码不一致";
    private static final String THE_OLD_PASSWORD_ERROR = "老密码错误";
    // 删除常量
    private static final String USER_DELETE_SUCCESS = "删除成功";
    // 查询
    private static final String USER_QUERY_SUCCESS= "查询成功";

    /**
    　* @author zhaochangxin
    　* @Description:用户登陆
    　* @Param param: User
     * @Param session: HttpSession
    　* @return: com.zcx.test.common.vo.ApiResult
    　* @date 2022/3/10 9:24
    　* @throws
    　*/
    @ApiOperation(value = "用户登陆", notes = "用户登录")
    @RequestMapping("/login")
    public ApiResult userLogin(User param,HttpSession session) throws UnknownHostException {
        // 通过用户名查询用户
        User user = userService.userLogin(param);
        if(user!=null)
        {
            // 新建springSecurity验证
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            // 验证密码
            boolean matches = passwordEncoder.matches(param.getPassword(), user.getPassword());
            if(matches)
            {
                if(user.getStatus()==1)
                {
                    // 生存Token
                    String token = JwtUtils.getToken(user);
                    // 存入redis
                    redisTemplate.opsForValue().set(LOGIN_USER_REDIS_POSITION + user.getId(), token);
                    session.setAttribute(LOGIN_USER_COOKIE, user);
                    // 调用日志控制层插入日志
                    logController.insertLog(user, LOGIN_SUCCESS);
                    // 返回登陆成功
                    return ApiResult.success(LOGIN_SUCCESS, token);
                }
                else
                {
                    return ApiResult.fail(PROHIBIT_LOGIN_USER);
                }
            }
            else
            {
                return ApiResult.fail(LOGIN_USER_PASSWORD_ERROR);
            }
        }
        return ApiResult.fail(LOGIN_USER_NOTFOUND);
    }

    /**
    　* @author zhaochangxin
    　* @Description:注册接口
    　* @Param user:
    　* @return: com.zcx.test.common.vo.ApiResult
    　* @date 2022/3/10 9:24
    　* @throws
    　*/
    @RequestMapping("/register")
    @ApiOperation(value = "用户注册", notes = "方法的备注说明")
    public ApiResult UserRegister(User user){
        // 首先判断是否有用户重名
        if(userService.userLogin(user)==null)
        {
            // 新建springSecurity加密密码
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            // 设置默认状态为登陆
            user.setStatus(1);
            // 设置创建人为1
            user.setCreated_by(BigInteger.valueOf(1));
            // 设置创建时间为当前时间
            user.setCreated_date(new java.sql.Date(new java.util.Date().getTime()));
            // 设置所有者
            user.setOwner("zcx");
            // 日志输出 user
            log.info(user.getUsername(),user);
            userService.userRegister(user);
            return ApiResult.success(REGISTER_SUCCESS);
        }
        return ApiResult.fail(REGISTER_USERNAME_REPEAT);
    }

    /**
     *
     * @param request
     * @param old_password 填入老密码
     * @param new_password 填入新密码
     * @param again_password 再填写一次
     * @return ApiResult
     */
    @RequestMapping("/updatePassword")
    @ApiOperation(value = "修改密码", notes = "方法的备注说明")
    public ApiResult userUpdatePassword(HttpServletRequest request,String old_password, String new_password, String again_password){
        // 获取http请求
        String user_id = request.getHeader("user_id");
        User loginUser = userService.queryUserById(user_id);
        // 验证密码
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(old_password, loginUser.getPassword());
        log.info(String.valueOf(matches));
        if(matches)
        {
            // 判断新密码与再次输入的密码是否相同
            if(new_password.equals(again_password))
            {
                // 加密新密码
                loginUser.setPassword(passwordEncoder.encode(new_password));
                userService.updatePassword(loginUser);
                return ApiResult.success(UPDATE_PASSWORD_SUCCESS);
            }
            else
            {
                return ApiResult.fail(THE_SECOND_PASSWORD_IS_INCONSISTENT);
            }
        }
        return ApiResult.success(THE_OLD_PASSWORD_ERROR);
    }

    /**
    　* @author zhaochangxin
    　* @Description:查询所有用户
    　* @Param param: UserQuery
    　* @return: com.zcx.test.common.vo.ApiResult<java.lang.Object>
    　* @date 2022/3/10 9:25
    　* @throws
    　*/
    @ApiOperation(value = "查询所有用户")
    @RequestMapping("/userList")
    public ApiResult<Object> getEmpList(UserQuery param) throws IOException {
        List<User> list=userService.queryUserList(param);
        System.out.println(list);
        Long count=userService.countUserList(param);
        EasyPoiUtils.exportExcel(User.class,list,"src/main/resources/excel/","userList.xls");
        return ApiResult.success(USER_OPERATION,list,count);
    }

    /**
    　* @author zhaochangxin
    　* @Description:通过id删除用户
    　* @Param ids:
    　* @return: com.zcx.test.common.vo.ApiResult
    　* @date 2022/3/10 9:25
    　* @throws
    　*/
    @ApiOperation(value = "通过id删除用户")
    @RequestMapping("/delete/{ids}")
    public ApiResult deleteUserById(@PathVariable("ids") String ids) {
        userService.deleteUserById(ids);
        return ApiResult.success(USER_DELETE_SUCCESS);
    }
    /**
    　* @author zhaochangxin
    　* @Description:通过id查询用户信息
    　* @Param id:
    　* @return: com.zcx.test.common.vo.ApiResult
    　* @date 2022/3/10 9:25
    　* @throws
    　*/
    @ApiOperation(value = "通过id查询用户信息")
    @RequestMapping("/{id}")
    public ApiResult queryUserById(@PathVariable("id") String id) {
        User user=userService.queryUserById(id);
        return ApiResult.success(USER_QUERY_SUCCESS,user);
    }

    @RequestMapping("/update/{ids}")
    public ApiResult updateUserRoleById(@PathVariable("ids")String ids,String user_id){
        List<String> list=new ArrayList<String>();
        Collections.addAll(list, StringUtils.splitByWholeSeparator(ids,","));
//        Collections.addAll(list);
        userService.deleteUserRoleById(user_id);
        userService.updateUserRoleById(list,user_id);
        return ApiResult.success("修改成功");
    }
}
